package lessson;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Week4 {

	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, ClassNotFoundException, InstantiationException {
		User u = new User();
		u.setAge(10);
		u.setName("nick");
		u.setScore(10);
		Map<Object, Object> a = BeanToMap((Object) u);
		System.out.println("MAP:");
		for (Object key : a.keySet()) {
			System.out.println((String) key + ":" + a.get(key));
		}
		System.out.println("BEAN:");
		System.out.println(MapToBean(a, "lessson.User"));
	}

	public static Map<Object, Object> BeanToMap(Object bean)
			throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HashMap<Object, Object> a = new HashMap<Object, Object>();
		Method[] md = bean.getClass().getDeclaredMethods();
		for (Method m : md) {
			if (m.getName().contains("get")) {
				String key = m.getName().replace("get", "");
				Object value = m.invoke(bean);
				a.put(key, value);
			}
		}
		return a;
	}

	public static Object MapToBean(Map a, String name) throws ClassNotFoundException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class cls = Class.forName(name);
		Object bean = cls.newInstance();
		for (Method m : cls.getDeclaredMethods()) {			
			if (m.getName().contains("set")) {
				String key = m.getName().replace("set", "");
				m.invoke(bean, a.get(key));
			}
		}
		return bean ;
	}

}
